import config from '@/config.js'
import {
	getStorage
} from '@/util/auth.js';
export function uploadFile(filePath) {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '上传中',
			mask: true,
		})
		uni.uploadFile({
			url: config.requestUrl + '/uploadFile',
			filePath,
			name: 'file',
			header: {
				'token': getStorage('token')
			},
			success: (e) => {
				uni.hideLoading()
				if (e.statusCode != 200) {
					uni.showToast({
						title: '上传失败',
						icon: 'none',
						mask: true,
					})
					reject();
				} else {
					const response = JSON.parse(e.data);
					switch (response.status) {
						case 200:
							resolve(response.result);
							break;
						case 405:
							uni.showToast({
								title: '登录信息已过期，请重新登录',
								icon: 'none',
								mask: true,
								duration: 2000,
								success: () => {
									Vue.prototype.$store.commit('user/SET_TOKEN', null)
									Vue.prototype.$store.commit('user/SET_USER', null)
									setTimeout(() => {
										uni.reLaunch({
											url: '/pages/index/index'
										})
									}, 2000)
								}
							})

							break;
						case 403:
							uni.showToast({
								title: '暂无权限',
								icon: 'none',
								duration: 2000,
								mask: true,
								success() {
									setTimeout(() => {
										reject();
									}, 2000)
								}
							})
							break;
						case 500:
							uni.showToast({
								title: response.message,
								icon: 'none',
								duration: 2000,
								mask: true,
								success() {
									setTimeout(() => {
										reject();
									}, 2000)
								}
							})
							break;
						default:
							uni.showToast({
								title: response.message,
								icon: 'none',
								duration: 2000,
								mask: true,
								success() {
									setTimeout(() => {
										reject();
									}, 2000)
								}
							})
							break;
					}
				}
			},
			fail: (res) => {
				uni.hideLoading()
				uni.showToast({
					title: '上传失败',
					mask: true
				})
				reject(res)
			}
		})
	})
}
export function downloadFile(url) {
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url,
			success: (res) => {
				resolve(res)
			},
			fail: (res) => {
				reject(res)
			}
		})
	})
}